package com.niodata.dp.task.dao.handler;

import com.niodata.dp.mybatis.DpMybatisTypeHandler;
import com.niodata.dp.task.entity.PackageParams;
import com.niodata.dp.task.entity.v2.PackageParamsV2;
import com.niodata.dp.util.JsonUtil;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.logging.log4j.util.Strings;

public class PackageParamsV2TypeHandler extends BaseTypeHandler<PackageParamsV2>
    implements DpMybatisTypeHandler {

  @Override
  public JdbcType getJdbcType() {
    return JdbcType.LONGNVARCHAR;
  }

  @Override
  public Class getTypeHandlerClass() {
    return PackageParamsV2TypeHandler.class;
  }

  @Override
  public Class getJavaClass() {
    return PackageParamsV2.class;
  }

  @Override
  public void setNonNullParameter(PreparedStatement preparedStatement, int i,
      PackageParamsV2 packageParamsV2, JdbcType jdbcType) throws SQLException {
    try {
      String json = JsonUtil.toJson(packageParamsV2);
      preparedStatement.setString(i, json);
    } catch (IOException e) {
      //e.printStackTrace();
    }
  }

  @Override
  public PackageParamsV2 getNullableResult(ResultSet resultSet, String s) throws SQLException {
    String json = resultSet.getString(s);
    if (Strings.isBlank(json)) {
      return null;
    }

    PackageParamsV2 v2 = null;
    try {
      v2 = JsonUtil.fromJson(PackageParamsV2.class, json);
    } catch (Exception ex) {
      //
    }
    if (v2 == null || v2.getGroups() == null) {
      try {
        PackageParams params = JsonUtil.fromJson(PackageParams.class, json);
        v2 = PackageParamsV2.buildFromPackageParams(params);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return v2;
  }

  @Override
  public PackageParamsV2 getNullableResult(ResultSet resultSet, int i) throws SQLException {
    String json = resultSet.getString(i);
    if (Strings.isBlank(json)) {
      return null;
    }
    PackageParamsV2 v2 = null;
    try {
      v2 = JsonUtil.fromJson(PackageParamsV2.class, json);
    } catch (Exception ex) {
      //
    }

    if (v2 == null || v2.getGroups() == null) {
      try {
        PackageParams params = JsonUtil.fromJson(PackageParams.class, json);
        v2 = PackageParamsV2.buildFromPackageParams(params);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    return v2;
  }

  @Override
  public PackageParamsV2 getNullableResult(CallableStatement callableStatement, int i)
      throws SQLException {
    return null;
  }
}
